<template>
  <el-card style="height: 500px">
    <el-form label-width="80px" style="width: 500px">
      <el-form-item label="头像">
        <!--   上传组件开始
         action设置文件上传的地址
         name设置上传的参数名称
         limit设置上传的数量
         -->
        <el-upload
            v-model:file-list="fileList"
            action="http://localhost:8080/v1/upload"
            name="file"
            limit="1"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image"/>
        </el-dialog>
        <!--   上传组件结束   -->
      </el-form-item>
      <el-form-item label="昵称">
        <el-input placeholder="请输入昵称" v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input :value="user.username" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save()">保存修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import {ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'


const user = {}; //ref(getUser());

const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  user.value.imgUrl=null;
  console.log(uploadFile, uploadFiles)
  //服务器发出删除文件的请求
  //得到图片路径 (服务器删除图片需要路径) uploadFile.response= JsonResult
  console.log(uploadFile.response.data);
  let url = uploadFile.response.data;
  axios.post(BASE_URL+'/v1/remove?url=' + url)
      .then((response) => {
        if (response.data.code == 1) {
          console.log("服务器图片删除完成!");
        }
      })
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
const handleSuccess = (response,uploadFile,uploadFiles)=>{
  // response=uploadFile.response=JsonResult
  user.value.imgUrl = response.data; //把上传成功的图片路径给到user对象
}
//点击保存的方法
const save = ()=>{
  let data = qs.stringify(user.value);
  console.log(data); //检查浏览器控制台输出的内容是否包含imgUrl图片路径
  //发出修改的请求
  axios.post('http://localhost:8080/v1/users/update',data)
      .then((response)=>{
        if (response.data.code==1){
          alert("修改成功!");
          //更新前端LocalStorage里面的数据
          localStorage.user = JSON.stringify(user.value);
          //刷新页面
          location.reload();
        }
      })
}

</script>

<style scoped>

</style>

